import { mapState } from 'vuex'
import workTime from './workTime'

export default {
  mixins: [workTime],
  
  data() {
    return {
      timer: null,
      currentDateTime: '',
      paydayCountdown: {
        days: '00',
        hours: '00',
        minutes: '00',
        seconds: '00'
      }
    }
  },

  computed: {
    nextPayday() {
      const now = new Date()
      const currentDay = now.getDate()
      const payday = this.workSettings.payday || 15
      const paydayTime = this.workSettings.paydayTime || '12:00'
      const payParts = paydayTime.split(':')
      const payHour = payParts[0]
      const payMinute = payParts[1]
      let nextPaydayDate = new Date(now.getFullYear(), now.getMonth(), payday, parseInt(payHour), parseInt(payMinute), 0)
      
      // 如果当前日期已过发薪日，计算下个月的发薪日
      if (currentDay > payday) {
        nextPaydayDate = new Date(now.getFullYear(), now.getMonth() + 1, payday, parseInt(payHour), parseInt(payMinute), 0)
      }
      
      return nextPaydayDate.toLocaleDateString('zh-CN', {
        month: 'long',
        day: 'numeric'
      }) + ' ' + paydayTime
    }
  },

  methods: {
    startTimer() {
      this.updateTime()
      this.timer = setInterval(this.updateTime, 1000)
    },

    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    },

    updatePaydayCountdown() {
      const now = new Date()
      const currentDay = now.getDate()
      const payday = this.workSettings.payday || 15
      const paydayTime = this.workSettings.paydayTime || '12:00'
      const payParts = paydayTime.split(':')
      const payHour = payParts[0]
      const payMinute = payParts[1]
      let nextPaydayDate = new Date(now.getFullYear(), now.getMonth(), payday, parseInt(payHour), parseInt(payMinute), 0)
      
      // 如果当前日期已过发薪日，计算下个月的发薪日
      if (currentDay > payday) {
        nextPaydayDate = new Date(now.getFullYear(), now.getMonth() + 1, payday, parseInt(payHour), parseInt(payMinute), 0)
      }
      
      const diffMs = nextPaydayDate - now
      const days = Math.floor(diffMs / (1000 * 60 * 60 * 24))
      const hours = Math.floor((diffMs % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
      const minutes = Math.floor((diffMs % (1000 * 60 * 60)) / (1000 * 60))
      const seconds = Math.floor((diffMs % (1000 * 60)) / 1000)
      
      this.paydayCountdown = {
        days: days.toString().padStart(2, '0'),
        hours: hours.toString().padStart(2, '0'),
        minutes: minutes.toString().padStart(2, '0'),
        seconds: seconds.toString().padStart(2, '0')
      }
    },

    updateTime() {
      const now = new Date()
      this.currentDateTime = this.formatDateTime(now)
      this.updatePaydayCountdown()
    }
  }
} 